import java.util.*;

// TreeMap和TreeSet
// HashMap和HashSet
class Student{
    public int id;
    public String name;

    public Student(int id, String name){
        this.id = id;
        this.name = name;
    }

    @Override
    public String toString() {
        return "(id:" + id + ",name:" + name + ")";
    }
}

public class Main {
    public static void main(String[] args) {
        // TreeMap底层是红黑树,关于key有序，TreeMap的ket唯一且非空
        Map<String, Integer> map1 = new TreeMap<>();
        map1.put("lisi",12);
        map1.put("wangwu",37);
        map1.put("zhaoliu",89);
        map1.put("xiaosi",42);
        System.out.println("TreeMap:");
        System.out.print("map1:");
        System.out.println(map1);
        // TreeMap(父接口的父接口)实现了SortedMap接口，表明是需要实现排序功能的Map接口
        // 要求key可比较,所以以下的代码中，Student的类必须是可比较的
        Map<Student,Integer> map2 = new TreeMap<>(new Comparator<Student>() {
            @Override
            public int compare(Student o1, Student o2) {
                return o1.name.compareTo(o2.name);   // 以Student对象的name为比较对象
            }
        });
        map2.put(new Student(1,"zhangsan"),10);
        map2.put(new Student(2,"lisi"),10);
        //map2.put(null,10); //TreeMap的key不能为null


        System.out.print("map2:");
        System.out.println(map2);




        // HashMap，key唯一，key和value可以为空，无序，底层是哈希桶
        System.out.println("HashMap:");
        Map<String,Integer> map3 = new HashMap<>();
        map3.put("lisi",12);
        map3.put("wangwu",37);
        map3.put("zhaoliu",89);
        map3.put(null,null);   // HashMap的key和value都可以为null
        System.out.print("map3:");
        System.out.println(map3);




        System.out.println("===============================================================");
        System.out.println("TreeSet:");
        // Set的key唯一，Set功能:对key去重
        // TreeSet实现了SortedSet接口，表明是需要实现排序功能的Set，Student必须是可比较的。TreeSet底层是TreeMap,所以TreeSet再底层是红黑树
        Set<Student> set1 = new TreeSet<>(new Comparator<Student>() {
            @Override
            public int compare(Student o1, Student o2) {
                return o1.id - o2.id;  // 以id为比较对象
            }
        });
        set1.add(new Student(1,"wangwu"));  // 这个Student对象为set的key
        set1.add(new Student(2,"wangwu"));
        // set1.add(null);   // TreeSet的底层是TreeMap，key不能是null
        System.out.println(set1);


        System.out.println("HashSet:");
        Set<Integer> set2 = new HashSet<>();
        set2.add(15);
        set2.add(28);
        set2.add (null);   // HashSet的底层是HashMap，key可以为null。

        System.out.println(set2);

    }
}
